<template>
  <n-flex justify="center" align="center">
    <n-card title="登录">
      <n-form
          ref="formRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          require-mark-placement="left"
          :model="formValue"
          :rules="rules"
          :size="size"
      >
        <n-form-item label="账号" path="user.name">
          <n-input round v-model:value="formValue.user.name" placeholder="输入账号" />
        </n-form-item>
        <n-form-item label="密码" path="user.password">
          <n-input round type="password" v-model:value="formValue.user.password" placeholder="输入密码" />
        </n-form-item>
        <n-form-item label="验证码" path="code">
          <n-input style="margin-right: 5px" v-model:value="formValue.code" placeholder="验证码" />
          <n-button tertiary type="info" @click="yzm">
            {{ issum }}
          </n-button>
        </n-form-item>
        <n-form-item>
          <n-button :loading="loading" class="n-button-dl" attr-type="button" type="primary" @click="handleValidateClick">
            验证
          </n-button>
        </n-form-item>
      </n-form>
    </n-card>
  </n-flex>

  <n-alert v-if="isData == 1" style="position: absolute; top: 0; width: 100vw; text-align: center" title="提示" type="success">
    登录成功
  </n-alert>
  <n-alert v-if="isData == 2" style="position: absolute; top: 0; width: 100vw; text-align: center" title="提示" type="info">
    密码错误！
  </n-alert>
  <n-alert v-if="isData == 3" style="position: absolute; top: 0; width: 100vw; text-align: center" title="提示" type="info">
    验证码错误！
  </n-alert>
  <n-alert v-if="isData == 4" style="position: absolute; top: 0; width: 100vw; text-align: center" title="提示" type="info">
    请输入验证码！
  </n-alert>
</template>

<script setup lang="ts">
import {ref, onMounted, watch, reactive} from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/userStore.ts'
import { login } from '../api/login.ts'
import type { FormInst } from 'naive-ui'
import { useMessage } from 'naive-ui'

const router = useRouter()
const userStore = useUserStore()
const message = useMessage() // 初始化 message


const formRef = ref<FormInst | null>(null)
const size = ref<'small' | 'medium' | 'large'>('medium')

const formValue = reactive({
  user: {
    name: 'admin',
    password: ''
  },
  code: null,
})

const rules = {
  user: {
    name: {
      required: false,
      message: '请输入姓名',
      trigger: 'blur'
    },
    password: {
      required: false,
      message: '请输入密码',
      trigger: ['input', 'blur']
    }
  },
  code: {
    required: false,
    message: '请输入验证码',
    trigger: ['input']
  }
}

// 验证码
const sum = ref()
const issum = ref()

function yzm() {
  const number1 = Math.floor(Math.random() * 90) + 10
  const number2 = Math.floor(Math.random() * 90) + 10
  sum.value = number1 + number2
  formValue.code = number1 + number2
  issum.value = `${number1} + ${number2} = ?`
}

function ifYzm(sumYzm: number) {
  return sum.value == sumYzm;
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

async function hideAlertAfterDelay() {
  await sleep(3000)
  isData.value = 0
}

const loading = ref(false)
const isData = ref(0)

async function handleValidateClick() {
  loading.value = true
  if (formValue.code == null) {
    isData.value = 4
    hideAlertAfterDelay()
    loading.value = false
    yzm()
    return
  } else if (!ifYzm(Number(formValue.code))) {
    isData.value = 3
    hideAlertAfterDelay()
    loading.value = false
    yzm()
    return
  }

  try {
    const res = await login(formValue.user.name, formValue.user.password)
    if (res.code == 200) {
      console.log(res.data)
      const name: string = res.data.name
      const token: string = res.data.token
      const router: string = res.data.router // 假设 roles 是 'admin', 'teacher' 等
      const id: number = res.data.id
      const studengOrteacherId: number = res.data.studengOrteacherId

      // 调用 setUserInfo，但**不在这里立即跳转**
      userStore.setUserInfo(name, token, router,id,studengOrteacherId)
      isData.value = 1
      hideAlertAfterDelay()

      message.success('登录成功，正在跳转...')

    } else {
      isData.value = 2
      hideAlertAfterDelay()
      message.error('密码错误！')
    }
  } catch (e) {
    console.error('登录失败:', e)
    message.error('登录请求失败，请检查网络或联系管理员。')
  } finally {
    loading.value = false
  }
}

// 4. 新增：使用 watch 监听 userStore.userInfo.role 的变化
watch(
    () => userStore.userInfo.router,
    (newRole) => {
      // 只有当 newRole 不为空，并且当前不在登录页时，才执行跳转
      // 这是为了防止在页面刷新时，从 localStorage 恢复状态后也触发这个 watch
      if (newRole && router.currentRoute.value.path === '/login') {
        // 跳转到目标页面
        router.push('/main/home')
      }
    }
)

onMounted(() => {
  yzm()
})
</script>

<style scoped lang="scss">
.n-flex {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(to bottom right, dodgerblue, white);

  .n-card {
    max-width: 400px;
    max-height: 700px;
  }
}

.n-button-dl {
  width: 100%;
}
</style>
